package com.huabo.audit.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.enums.ProcessVariableEnum;
import com.hbfk.util.JsonBean;
import com.hbfk.util.PageInfo;
import com.hbfk.util.ResponseFormat;
import com.huabo.audit.enums.ProcessEnum;
import com.huabo.audit.oracle.entity.AgentEntity;
import com.huabo.audit.oracle.entity.TblAttachment;
import com.huabo.audit.oracle.entity.TblAuditOption;
import com.huabo.audit.oracle.entity.TblCirculation;
import com.huabo.audit.oracle.entity.TblNbsjProject;
import com.huabo.audit.oracle.entity.TblReportEntity;
import com.huabo.audit.oracle.mapper.TblAttachmentMapper;
import com.huabo.audit.oracle.mapper.TblCirculationMapper;
import com.huabo.audit.oracle.mapper.TblNbsjAuditplanMapper;
import com.huabo.audit.oracle.mapper.TblNbsjPlanProjectMapper;
import com.huabo.audit.oracle.mapper.TblReportMapper;
import com.huabo.audit.oracle.vo.TblReportVo;
import com.huabo.audit.service.ActivityPluginsService;
import com.huabo.audit.service.ProcessService;
import com.huabo.audit.service.TblAuditOptionService;
import com.huabo.audit.service.TblNbsjProjectService;
import com.huabo.audit.service.TblReportService;
import com.huabo.audit.util.R;
@Service
public class TblReportServiceImpl implements TblReportService {
	
	@Autowired
	private TblReportMapper tblReportMapper;
    
    @Autowired
    private ActivityPluginsService activityPluginsService;
    @Resource
    private TblNbsjAuditplanMapper tblNbsjAuditplanMapper;
    @Resource
	private TblAttachmentMapper tblAttachmentMapper;
    @Resource
	public TblNbsjPlanProjectMapper tblNbsjPlanProjectMapper;
    
    @Resource
   	public TblCirculationMapper tblCirculationMapper;
    
    @Resource
    private TblNbsjProjectService tblNbsjProjectService;
    
    @Resource
	private RuntimeService runtimeService;
	@Resource
	private HistoryService historyService;
	@Resource
	private RepositoryService repositoryService;
	@Resource 
	private TaskService taskService;
    @Resource
    private ProcessService processService;
    
    @Resource
    private TblAuditOptionService tblAuditOptionService;
	@Override
	public void add(TblReportEntity tblReport) {
		// TODO Auto-generated method stub

	}

	@Override
	public List findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void detele(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public TblReportEntity findByid(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void modify(TblReportEntity tblReport) {
		// TODO Auto-generated method stub

	}

	@Override
	public List search(String name, String time) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TblReportEntity> findReportByProjectId(Integer projectid, String reportType, Integer reportStatus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TblReportEntity> findNoReportByProjectId(Integer projectid) {

		List<TblReportEntity> list = this.tblReportMapper.findNoReportByProjectId(projectid);
		
		if(null!=list&&list.size()!=0) {
			return list;
		}
		return null;
		
	}

	
	
	//==
	@Override
	public JsonBean zdyPageList(String token, Integer pageNumber, Integer pageSize, TblReportVo tblReportVo,Integer projectId)
			throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if(loginStaff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		
		BigDecimal orgid = loginStaff.getCurrentOrg().getOrgid();
		
    	if(pageNumber == null) {
    		pageNumber = 1;
    	}
    	if(pageSize==null) {
    		pageSize=15;
    	}
    	Map<String,Object> resultMap = new HashMap<String,Object>(0);
    	
    	
    	if(null == projectId) {
    		//==查询当前实施的项目！
    		TblNbsjProject tnp = this.tblNbsjProjectService.getCurrenNbsjProjectByLoginStaff(loginStaff.getStaffid());
    		if(tnp == null) {
    			return ResponseFormat.retParam(0,30003,resultMap);
    		}
    		projectId = tnp.getProjectId();
    	}
    	
    	
    	PageInfo<TblReportEntity> pageInfo = new PageInfo<TblReportEntity>();
//    	tblNbsjWorkReport.setAuditorgid(loginStaff.getCurrentOrg().getOrgid());
//    	pageInfo.setCondition(tblNbsjWorkReport);
    	pageInfo.setPageSize(pageSize);
    	pageInfo.setCurrentPage(pageNumber);
    	pageInfo.setTlist(this.tblReportMapper.selectListByPageInfo(pageInfo,tblReportVo,orgid.intValue(),projectId));
    	pageInfo.setTotalRecord(this.tblReportMapper.selectCountByPageInfo(pageInfo,tblReportVo,orgid.intValue(),projectId));
    	pageInfo.getTotalPage();
    	String identifier = activityPluginsService.getoNState(ProcessEnum.SJ_JHGL.name());
    	resultMap.put("identifier", identifier);
    	resultMap.put("pageInfo", pageInfo);
    	return ResponseFormat.retParam(1,200,resultMap);
	}

	@Override
	public JsonBean zdyAdd(TblReportEntity report, String token,String attids) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if(loginStaff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		
		Integer orgid = loginStaff.getCurrentOrg().getOrgid().intValue();
		report.setOrgid(orgid);
		
		
		//==
		//==查询当前实施的项目！
		TblNbsjProject tnp = this.tblNbsjProjectService.getCurrenNbsjProjectByLoginStaff(loginStaff.getStaffid());
		if(tnp == null) {
			return ResponseFormat.retParam(0,30003,null);
		}
		Integer projectId = tnp.getProjectId();
		
		report.setProjectId(new BigDecimal(projectId));
		
		
//		Integer count = this.tblReportMapper.selectPlanCodeByOrgid(report);
//		if(count > 0) {
//			return ResponseFormat.retParam(0,202,null);
//		}
    	
//		report.setCreatestaffid(loginStaff.getStaffid()+"");
		report.setSendTime(new Date());
		report.setReportstatus(0);
		//根据planId主键是否为空判断新增还是修改 ，主键为空新增、不为空修改；
		
		if(report.getReportid() != null) {
			//修改；
			//this.tblReportMapper.updateEntity(report);
			tblReportMapper.updateByPrimaryKeySelective(report);
			//==附件，先删除 再重新添加
			this.tblReportMapper.deleteAttmentRelationREPORT(report.getReportid().intValue());
			if (attids != null && !"".equals(attids)) {
				String[] ids = attids.split(",");
				for (String id : ids) {
					this.tblReportMapper.insertAttmentRelationREPORT(id, report.getReportid().intValue());
				}
			}
		}else {
			//新增；
			//this.tblReportMapper.insertEntity(report);
			tblReportMapper.insertSelective(report);
			//==附件
			if (attids != null && !"".equals(attids)) {
				String[] ids = attids.split(",");
				for (int i = 0; i < ids.length; i++) {
					String id = ids[i];
					this.tblReportMapper.insertAttmentRelationREPORT(id, report.getReportid().intValue());
				}
			}
		}
		Map<String,Object> resultMap = new HashMap<String,Object>(0);
		resultMap.put("report",report);
		return ResponseFormat.retParam(1,200,resultMap);
	}

	@Override
	public JsonBean zdyDelete(Integer reportid, String token) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if(loginStaff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		TblReportEntity plan = this.tblReportMapper.selectById(reportid);
		
		if(plan == null) {
			return ResponseFormat.retParam(0,50001,null);
		}
		
//		if (plan.getOpinionstatus().equals(TblNbsjAuditplan.SPNO)) {
//			this.tblReportMapper.deleteAuditPlanEntityById(planId);
//			return ResponseFormat.retParam(0,200,null);
//        } else {
//            return ResponseFormat.retParam(0,50001,null);
//        }
		this.tblReportMapper.deleteById(reportid);
		return ResponseFormat.retParam(1,200,null);
	}

	@Override
	public JsonBean findZdyReportDetail(String token, Integer reportid) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if(loginStaff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		Map<String,Object> resultMap = new HashMap<String,Object>(0);
		
		TblReportEntity plan = this.tblReportMapper.selectById(reportid);
		resultMap.put("report", plan);
		return ResponseFormat.retParam(1,200,resultMap);
	}

	/**
	 * 报告编制-导出
	 */
	@Override
	public TblReportEntity findReportByreportId(String reportid){
		return this.tblReportMapper.getById(reportid);
	}

	@Override
	public JsonBean submitReportFhApproval(String token, Integer reportid) throws Exception {
		TblStaffUtil user = DealUserToken.parseUserToken(token);
		if(user == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
    	
    	TblReportEntity report = tblReportMapper.selectById(reportid);
        TblCirculation cir = new TblCirculation();
        try {
           
           cir.setCytype(TblCirculation.TYPE_SJBGFH);
           cir.setCycode(report.getReportid().toString());
           cir.setCyname(report.getReportname());
           cir.setCydate(new Date());
           cir.setCystate(TblCirculation.STATE_FQ);
           cir.setCyurl(TblCirculation.URL_SJBGFH+report.getReportid());
           cir.setCyStaffid(user.getStaffid().toString());
           this.tblCirculationMapper.saveTblCirculation(cir);
           
           Map<String, Object> variables= new HashMap<String, Object>();
           variables.put(ProcessVariableEnum.model.toString(), cir);
   			AgentEntity ae = new AgentEntity();
   			ae.setReviewer(report.getFhstaffid());
   			if(report.getFhstaffid()==null) {
   				return ResponseFormat.retParam(0,"请添加报告复核人",null);
   			}
		   variables.put(ProcessVariableEnum.agent.toString(), ae);
           ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ProcessEnum.SJ_SJBGFH.name(),cir.getCyid().toString(), variables);
           Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
           cir.setTaskid(task.getId());
           //流程定义Id
           String businessKey = processInstance.getBusinessKey();
           String definitionId = processInstance.getProcessDefinitionId();
           cir.setBusinesskey(businessKey);
           cir.setDefinitionid(definitionId);
           this.tblCirculationMapper.updateCirculationInfoById(cir);
           taskService.complete(task.getId());
           report.setReportstatus(TblReportEntity.FHZ);
           report.setRepdesc(null);
           tblReportMapper.updateEntity(report);
        } catch (Exception e) {
        	e.printStackTrace();
        	if(cir != null && cir.getCyid() != null) {
        		this.tblCirculationMapper.deleteEntityById(cir.getCyid());
        	}
        	return ResponseFormat.retParam(0,30002,null);
        }	
        return ResponseFormat.retParam(1,200,null);

	}
	@Override
	public JsonBean submitReportZqyjApproval(String token, Integer reportid) throws Exception {
		TblStaffUtil user = DealUserToken.parseUserToken(token);
		if(user == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		
		TblReportEntity report = tblReportMapper.selectById(reportid);
		TblCirculation cir = new TblCirculation();
		try {
			
			cir.setCytype(TblCirculation.TYPE_SJBGZQYJ);
			cir.setCycode(report.getReportid().toString());
			cir.setCyname(report.getReportname());
			cir.setCydate(new Date());
			cir.setCystate(TblCirculation.STATE_FQ);
			cir.setCyurl(TblCirculation.URL_SJBGZQYJ+report.getReportid());
			cir.setCyStaffid(user.getStaffid().toString());
			this.tblCirculationMapper.saveTblCirculation(cir);
			
			Map<String, Object> variables= new HashMap<String, Object>();
			variables.put(ProcessVariableEnum.model.toString(), cir);
			AgentEntity ae = new AgentEntity();
			ae.setTakeAdvice(report.getZqyjstaffid());
			if(report.getFhstaffid()==null) {
				return ResponseFormat.retParam(0,"请添加报告征求意见人",null);
			}
			variables.put(ProcessVariableEnum.agent.toString(), ae);
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ProcessEnum.SJ_ZQYJ.name(),cir.getCyid().toString(), variables);
			Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
			cir.setTaskid(task.getId());
			//流程定义Id
			String businessKey = processInstance.getBusinessKey();
			String definitionId = processInstance.getProcessDefinitionId();
			cir.setBusinesskey(businessKey);
			cir.setDefinitionid(definitionId);
			this.tblCirculationMapper.updateCirculationInfoById(cir);
			taskService.complete(task.getId());
			report.setReportstatus(TblReportEntity.ZQYJ);
			report.setRepdesc(null);
			tblReportMapper.updateEntity(report);
		} catch (Exception e) {
			e.printStackTrace();
			if(cir != null && cir.getCyid() != null) {
				this.tblCirculationMapper.deleteEntityById(cir.getCyid());
			}
			return ResponseFormat.retParam(0,30002,null);
		}	
		return ResponseFormat.retParam(1,200,null);
		
	}
	public JsonBean submitReportSpApproval(String token, Integer reportid) throws Exception {
		TblStaffUtil user = DealUserToken.parseUserToken(token);
		if(user == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		
		TblReportEntity report = tblReportMapper.selectById(reportid);
		TblCirculation cir = new TblCirculation();
		try {
			
			cir.setCytype(TblCirculation.TYPE_SJBG);
			cir.setCycode(report.getReportid().toString());
			cir.setCyname(report.getReportname());
			cir.setCydate(new Date());
			cir.setCystate(TblCirculation.STATE_FQ);
			cir.setCyurl(TblCirculation.URL_SJBG+report.getReportid());
			cir.setCyStaffid(user.getStaffid().toString());
			this.tblCirculationMapper.saveTblCirculation(cir);
			
			Map<String, Object> variables= new HashMap<String, Object>();
			variables.put(ProcessVariableEnum.model.toString(), cir);
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ProcessEnum.SJ_SJBG.name(),cir.getCyid().toString(), variables);
			Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
			cir.setTaskid(task.getId());
			//流程定义Id
			String businessKey = processInstance.getBusinessKey();
			String definitionId = processInstance.getProcessDefinitionId();
			cir.setBusinesskey(businessKey);
			cir.setDefinitionid(definitionId);
			this.tblCirculationMapper.updateCirculationInfoById(cir);
			taskService.complete(task.getId());
	        report.setRepdesc(null);
			report.setReportstatus(TblReportEntity.SPZ);
			tblReportMapper.updateEntity(report);
		} catch (Exception e) {
			e.printStackTrace();
			if(cir != null && cir.getCyid() != null) {
				this.tblCirculationMapper.deleteEntityById(cir.getCyid());
			}
			return ResponseFormat.retParam(1,30002,null);
		}	
		return ResponseFormat.retParam(1,200,null);
		
	}
	@Override
	public JsonBean getReportFhApprovalInfo(String token, Integer reportid, String taskId, Integer cyId) throws Exception {
		TblStaffUtil staff = DealUserToken.parseUserToken(token);
		if(staff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		Map<String,Object> resultMap = new HashMap<String,Object>(0);
    	TblReportEntity report = tblReportMapper.selectById(reportid);
        List<String> btnList = null;
    	if(report!=null){
    		if(StringUtils.isNotBlank(taskId) && (report.getReportstatus()!=TblReportEntity.FHTZ||report.getReportstatus()!=TblReportEntity.XTZ)){
    			btnList = processService.getButtonsForTransition(taskId);
    			resultMap.put("btnList", btnList);
    		}
    		List<TblAuditOption> ao = tblAuditOptionService.findOptionByRelationId(report.getReportid().toString(),cyId);
    		if (cyId != null){
    			TblCirculation cy = this.tblCirculationMapper.findById(cyId.toString());
    			resultMap.put("cy", cy);
    		}
    		resultMap.put("taskId", taskId);
    		resultMap.put("aoptionList", ao);
    		resultMap.put("cyId", cyId);
    		resultMap.put("report", report);
    	}
    	return ResponseFormat.retParam(1,200,resultMap);
	}
	@Override
	public JsonBean dealReportFhApporvalInfo(String token, Integer cyId, String taskId, String transition,
			String optDesc, String reportid) throws Exception {
		TblStaffUtil staff = DealUserToken.parseUserToken(token);
		if(staff == null) {
			return ResponseFormat.retParam(0,20006,null);
		}
		JsonBean jsonBean = null;
		TblCirculation cy = this.tblCirculationMapper.findById(cyId.toString());
		if (null != cy) {
			Map<String, Object> variables = new HashMap<>();
			variables.put(ProcessVariableEnum.model.toString(), cy);
			if (StringUtils.isNotBlank(transition)) {
				variables.put(ProcessVariableEnum.transition.toString(), transition);
			}
			try {
				taskService.claim(taskId, staff.getStaffid().toString());
				taskService.complete(taskId, variables);
			} catch (Exception e) {
				e.printStackTrace();
				return ResponseFormat.retParam(0,30002,null);
			}
			//添加审批意见
			TblAuditOption opt = new TblAuditOption();
			opt.setCyid(cy.getCyid());
			opt.setOptStaffid(staff.getStaffid());
			opt.setStaffidName(staff.getRealname());
			opt.setOptDesc(optDesc);
			opt.setRelationId(new BigDecimal(reportid));
			opt.setOptState(transition);
			jsonBean = this.tblAuditOptionService.saveAuditOptionInfo(cy,opt);
		}
		return jsonBean;
	}

	@Override
	public R removeAttInfoByAttId(String token, String attId) throws Exception {
		TblStaffUtil loginStaff = DealUserToken.parseUserToken(token);
		if(loginStaff == null) {
			return R.fail("用户已失效！");
		}
        return this.deleteRealtionAttInfo(attId);
	}

	private R deleteRealtionAttInfo(String attId) throws Exception {
		boolean b = false;
        TblAttachment att = this.tblAttachmentMapper.selectEntityById(attId);
        this.tblReportMapper.deleteFileInfoByAttId(att.getAttid().intValue());
        this.tblAttachmentMapper.deleteEntity(att.getAttid());
        
        return R.success();
	}
}
